import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';

import 'node.dart';

class CSSLayout extends MultiChildRenderObjectWidget {
  final CSSNodeData data;

  CSSLayout(this.data)
      : super(key: ValueKey(data.uuid), children: data.childrenWidget);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return CSSLayoutRenderBox(data);
  }
}

class CSSLayoutRenderBox extends RenderBox
    with
        ContainerRenderObjectMixin<RenderBox, CSSNodeData>,
        RenderBoxContainerDefaultsMixin<RenderBox, CSSNodeData> {
  CSSNodeData data;

  CSSLayoutRenderBox(this.data);

  @override
  void setupParentData(RenderBox child) {
    if (child is CSSNodeRenderBox) {
      child.parentData = child.data;
      child.data.parent = data;
    }
  }

  @override
  void performLayout() {
    final BoxConstraints constraints = this.constraints;

    size = Size(200, 100);

    RenderBox? child = firstChild;

    while (child != null) {
      final CSSNodeData childParentData = child.parentData! as CSSNodeData;

      child.layout(constraints, parentUsesSize: true);
      child = childParentData.nextSibling;
    }
  }

  @override
  void debugAssertDoesMeetConstraints() {}

  @override
  bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
    return defaultHitTestChildren(result, position: position);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    defaultPaint(context, offset);
  }
}
